package com.example.myblog01.service.impl;

import com.example.myblog01.Util.MarkdownUtils;
import com.example.myblog01.dao.BlogServiceDao;
import com.example.myblog01.pojo.Blog;
import com.example.myblog01.pojo.Type;
import com.example.myblog01.service.BlogService;
import com.example.myblog01.vo.BlogQuery;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceimpl implements BlogService {

    @Autowired
    private BlogServiceDao blogServiceDao;


    @Override
    public Blog getBlog(Long id) {
        return blogServiceDao.getById(id);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {

//        Specification返回前端博客的综合查询
        return blogServiceDao.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
//                新建一个predicates列表 存储三个筛选条件是否选中   来动态查询分页 由Controller调用并显示在前端
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(blog.getTitle()) && blog.getTitle() != null) {
//                    拿到title的blog.getTitle()相似 命名 title
                    predicates.add(cb.like(root.<String>get("title"), "%" + blog.getTitle() + "%"));
                }
                if (blog.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                if (blog.isRecommend()) {
                    predicates.add(cb.equal(root.<Boolean>get("recommend"), blog.isRecommend()));
                }
//                上面的值转换为数组
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);

    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogServiceDao.findAll(pageable);
    }

    @Transactional
    @Override
    public Blog seveblog(Blog blog) {
//        如果是新增的额
        if (blog.getId() == null) {
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
//        浏览次数
            blog.setViews(0);
        } else {
//            否则
            blog.setUpdateTime(new Date());
        }


        return blogServiceDao.save(blog);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
//        查出要修改的对象
        Blog blog1 = blogServiceDao.getById(id);
        if (blog1 == null) {
            try {
                throw new NotFoundException("不存在");
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        }
//        否则更新数据库  把新数据给查出要修改的对象
        BeanUtils.copyProperties(blog1, blog);
        return blogServiceDao.save(blog1);
    }

    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogServiceDao.deleteById(id);
    }


    //    进行推荐的筛选 返回List
    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        return blogServiceDao.findTop(PageRequest.of(0, size, Sort.by(Sort.Direction.DESC, "updateTime")));

    }


    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogServiceDao.findByQuery(query, pageable);
    }


    @Override
    public Blog getAndConvert(Long id) {
        Blog blog = blogServiceDao.getById(id);
        if (blog == null) {
            try {
                throw new NotFoundException("该博客不存在");
            } catch (NotFoundException e) {
                System.out.println("------------异常--------------");
                e.printStackTrace();
            }
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog,b);
        String content = b.getContent();
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        return b;
    }

    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {
        return blogServiceDao.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join = root.join("tags");
                return cb.equal(join.get("id"),tagId);
            }
        },pageable);
    }


    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogServiceDao.findGroupYear();
        Map<String,List<Blog>> map = new HashMap<>();
        for (String year : years){
            map.put(year,blogServiceDao.findByYear(year));
        }
        return map;
    }

    @Override
    public Long countBlog() {
        return blogServiceDao.count();
    }
}
